package com.smartcampusbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smartcampusbackend.mapper.ClassCircleMapper;
import com.smartcampusbackend.mapper.ClassCircleMemberMapper;
import com.smartcampusbackend.mapper.UserMapper;
import com.smartcampusbackend.model.ClassCircle;
import com.smartcampusbackend.model.ClassCircleMember;
import com.smartcampusbackend.model.User;
import com.smartcampusbackend.service.ClassCircleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class ClassCircleServiceImpl implements ClassCircleService {

    @Autowired
    private ClassCircleMapper classCircleMapper;
    
    @Autowired
    private ClassCircleMemberMapper memberMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public ClassCircle createClassCircle(ClassCircle classCircle, Integer creatorId) {
        // 检查创建者是否为教师
        User creator = userMapper.selectById(creatorId);
        if (creator == null) {
            throw new RuntimeException("用户不存在");
        }
        
        if (!"TEACHER".equals(creator.getRole())) {
            throw new RuntimeException("只有教师可以创建班级圈");
        }
        
        // 检查realName是否为空
        if (creator.getRealName() == null || creator.getRealName().trim().isEmpty()) {
            throw new RuntimeException("用户真实姓名不能为空，请完善个人信息");
        }
        
        // 检查班级ID是否已存在
        ClassCircle existing = classCircleMapper.findByClassId(classCircle.getClassId());
        if (existing != null) {
            throw new RuntimeException("班级ID已存在");
        }
        
        // 设置创建信息
        classCircle.setCreatorId(creatorId);
        classCircle.setCreatorName(creator.getRealName().trim());
        classCircle.setMemberCount(1);
        classCircle.setCreateTime(LocalDateTime.now());
        classCircle.setUpdateTime(LocalDateTime.now());
        
        // 保存班级圈
        classCircleMapper.insert(classCircle);
        
        // 创建者自动加入班级圈
        ClassCircleMember member = new ClassCircleMember();
        member.setClassCircleId(classCircle.getId());
        member.setUserId(creatorId);
        member.setUserName(creator.getRealName().trim());
        member.setUserRole(creator.getRole());
        member.setJoinType("CREATOR");
        member.setJoinTime(LocalDateTime.now());
        member.setStatus(1);
        memberMapper.insert(member);
        
        return classCircle;
    }

    @Override
    @Transactional
    public boolean deleteClassCircle(Integer classCircleId, Integer userId) {
        ClassCircle classCircle = classCircleMapper.selectById(classCircleId);
        if (classCircle == null) {
            throw new RuntimeException("班级圈不存在");
        }
        // 获取当前用户
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        // 检查是否为创建者或管理员
        if (!classCircle.getCreatorId().equals(userId) && !"ADMIN".equals(user.getRole())) {
            throw new RuntimeException("只有创建者或管理员可以删除班级圈");
        }
        // 先删除所有成员记录
        memberMapper.deleteByClassCircleId(classCircleId);
        // 然后物理删除班级圈记录
        classCircleMapper.deleteById(classCircleId);
        return true;
    }

    @Override
    public ClassCircle searchByClassId(String classId) {
        return classCircleMapper.findByClassId(classId);
    }

    @Override
    @Transactional
    public boolean joinClassCircle(Integer classCircleId, Integer userId) {
        // 检查班级圈是否存在
        ClassCircle classCircle = classCircleMapper.selectById(classCircleId);
        if (classCircle == null) {
            throw new RuntimeException("班级圈不存在或已删除");
        }
        
        // 检查用户是否已加入
        if (isUserJoined(classCircleId, userId)) {
            throw new RuntimeException("您已加入该班级圈");
        }
        
        // 获取用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查realName是否为空
        if (user.getRealName() == null || user.getRealName().trim().isEmpty()) {
            throw new RuntimeException("用户真实姓名不能为空，请完善个人信息");
        }
        
        // 添加成员
        ClassCircleMember member = new ClassCircleMember();
        member.setClassCircleId(classCircleId);
        member.setUserId(userId);
        member.setUserName(user.getRealName().trim());
        member.setUserRole(user.getRole());
        member.setJoinType("MEMBER");
        member.setJoinTime(LocalDateTime.now());
        member.setStatus(1);
        memberMapper.insert(member);
        
        // 更新成员数量
        int memberCount = memberMapper.countByClassCircleId(classCircleId);
        classCircleMapper.updateMemberCount(classCircleId, memberCount);
        
        return true;
    }

    @Override
    @Transactional
    public boolean leaveClassCircle(Integer classCircleId, Integer userId) {
        // 检查是否为创建者
        ClassCircle classCircle = classCircleMapper.selectById(classCircleId);
        if (classCircle != null && classCircle.getCreatorId().equals(userId)) {
            throw new RuntimeException("创建者不能退出班级圈，请删除班级圈");
        }
        
        // 删除成员记录
        QueryWrapper<ClassCircleMember> wrapper = new QueryWrapper<>();
        wrapper.eq("class_circle_id", classCircleId)
               .eq("user_id", userId);
        memberMapper.delete(wrapper);
        
        // 更新成员数量
        int memberCount = memberMapper.countByClassCircleId(classCircleId);
        classCircleMapper.updateMemberCount(classCircleId, memberCount);
        
        return true;
    }

    @Override
    public List<ClassCircle> getUserCreatedCircles(Integer userId) {
        return classCircleMapper.findByCreatorId(userId);
    }

    @Override
    public List<ClassCircle> getUserJoinedCircles(Integer userId) {
        return classCircleMapper.findUserJoinedCircles(userId);
    }

    @Override
    public List<ClassCircle> getAllClassCircles() {
        return classCircleMapper.selectList(null);
    }

    @Override
    public List<ClassCircleMember> getClassCircleMembers(Integer classCircleId) {
        return memberMapper.findByClassCircleId(classCircleId);
    }

    @Override
    public boolean isUserJoined(Integer classCircleId, Integer userId) {
        ClassCircleMember member = memberMapper.findByUserAndCircle(userId, classCircleId);
        return member != null;
    }

    @Override
    @Transactional
    public boolean removeClassCircleMember(Integer classCircleId, Integer memberId, Integer operatorUserId, boolean isAdmin) {
        // 检查班级圈是否存在
        ClassCircle classCircle = classCircleMapper.selectById(classCircleId);
        if (classCircle == null) {
            throw new RuntimeException("班级圈不存在");
        }
        // 检查操作者是否为班级圈创建者或管理员
        if (!isAdmin && !classCircle.getCreatorId().equals(operatorUserId)) {
            throw new RuntimeException("无权操作");
        }
        // 检查要删除的成员是否存在
        ClassCircleMember member = memberMapper.selectById(memberId);
        if (member == null) {
            throw new RuntimeException("成员不存在");
        }
        // 检查成员是否属于该班级圈
        if (!member.getClassCircleId().equals(classCircleId)) {
            throw new RuntimeException("成员不属于该班级圈");
        }
        // 检查是否为创建者自己
        if (member.getJoinType().equals("CREATOR")) {
            throw new RuntimeException("不能删除班级圈创建者");
        }
        // 删除成员记录
        memberMapper.deleteById(memberId);
        // 更新成员数量
        int memberCount = memberMapper.countByClassCircleId(classCircleId);
        classCircleMapper.updateMemberCount(classCircleId, memberCount);
        return true;
    }
} 